/*================================================================
*   Copyright (C) 2020 belonging to YangZhengQing. All rights reserved.
*   
*   文件名称：opefun.c
*   创 建 者：YangZhengQing
*   创建日期：2020年02月10日
*   描    述：栈的操作函数
*
*================================================================*/
#include "global.h"

/*栈相关宏定义*/
#define STACK_INIT_SIZE 20//栈初始化大小
#define STACKINRECMENT 10//栈扩容大小

/*栈初始化函数*/

void stack_init(stack *s)
{
	s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
	if(!s->base)
	{
		printf("分配栈空间错误：%s\n",strerror(errno));
		exit(0);
	}

	s->top = s->base;
	s->stack_size = STACK_INIT_SIZE;
}

/*入栈函数*/
void push(stack *s,ElemType c)
{
	/*判断是否溢出栈,如果溢出，则扩容*/
	if(s->top - s->base >= STACK_INIT_SIZE)
	{
		s->base = (ElemType *)realloc(s->base,(s->stack_size + STACKINRECMENT)*sizeof(ElemType));
		if(!s->base)
		{
			printf("栈扩容失败：%s\n",strerror(errno));
			exit(0);
		}
	}
	*(s->top) = c;
	s->top++;
}

/*出栈函数*/
void pop(stack *s,ElemType *c)
{
	if(s->top == s->base)
	{
		printf("栈已空!\n");
		return;
	}
	*c = *--(s->top);
}

/*计算当前栈的大小函数*/
int current_size(stack s)
{
	return (s.top - s.base);
}

/*清空一个栈函数*/
void clear_stack(stack *s)
{
	s->top = s->base; 
}

/*释放栈函数*/
void destory_stack(stack *s)
{
	int i ;
	int len = s->stack_size;

	for(i = 0;i<len;i++)
	{
		free(s->base);
		s->base++;
	}
	s->base = s->top=NULL;
	s->stack_size = 0;
}
